﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Windows.Forms;
using OrionApplication.OrionForm;
using OrionApplication.OrionLib;
using OrionApplication.OrionLib.Dao;
using OrionApplication.OrionLib.Orion;

namespace OrionApplication
{
    public partial class Main : ComponentFactory.Krypton.Toolkit.KryptonForm
    {
        public Main()
        {
            InitializeComponent();
        }

        #region gestion des lignes du treeview menu
        private void RempliskCbMenu()
        {
            DaoOrionTable dao = new DaoOrionTable();
            List<OrionTable> lMenu = dao.SelectByIdent("MENU", true);
            kMenuListe.DataSource = lMenu;
        }

        private void RempliLigneMenu()
        {
            tvMenuMain.Nodes.Clear();
            DaoOrionMenu daoOM = new DaoOrionMenu();
            List<OrionMenu> lom = daoOM.SelectAll(Convert.ToInt32(kMenuListe.SelectedValue));
            foreach (OrionMenu om in lom)
            {
                if (DroitSurMenu(om))
                {
                    TreeNode tn = new TreeNode(om.Libelle);
                    tn.ImageIndex = om.OrionImageId;
                    tn.SelectedImageIndex = om.OrionImageId;
                    tn.Name = om.OrionId.ToString();
                    tn = this.GetChildrenMenu(om.OrionId, tn);
                    tvMenuMain.Nodes.Add(tn);
                }
            }
        }

        private TreeNode GetChildrenMenu(Int32 OrionMenuIdParentP, TreeNode OrionMenuParent)
        {
            TreeNode retour = OrionMenuParent;
            DaoOrionMenu daoOM = new DaoOrionMenu();
            List<OrionMenu> lom = daoOM.SelectAllChild(OrionMenuIdParentP);
            foreach (OrionMenu om in lom)
            {
                if (DroitSurMenu(om))
                {
                    TreeNode temp = new TreeNode();
                    temp = new TreeNode(om.Libelle);
                    temp.ImageIndex = om.OrionImageId;
                    temp.SelectedImageIndex = om.OrionImageId;
                    temp.Name = om.OrionId.ToString();
                    temp = this.GetChildrenMenu(om.OrionId, temp);
                    retour.Nodes.Add(temp);
                }
            }
            return retour;
        }

        private bool DroitSurMenu(OrionMenu om)
        {
            bool retour = false;
            if (((Boolean)CallContext.GetData(OrionConfBase.OrionUserIsAdmin)))
                retour = true;
            else
            {
                DaoOrionGroupMenu daoGM = new DaoOrionGroupMenu();
                if (daoGM.IsMenu4Group(((OrionGroup)CallContext.GetData(OrionConfBase.OrionUserGroupConnected)).OrionId, om.OrionId))
                    retour = true;
                DaoOrionUserMenu daoUM = new DaoOrionUserMenu();
                if (daoUM.IsMenu4User(((OrionUser)CallContext.GetData(OrionConfBase.OrionUserConnected)).OrionId, om.OrionId))
                    retour = true;
            }
            return retour;
        }
        #endregion

        #region Gestion du Menu bandeau
        private void quitterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        #region Choix de l'Interface
        private void SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager pm)
        {
            this.OrionKryptonManager.GlobalPaletteMode = pm;
        }

        private void tsChoixOffice2010Noir_Click(object sender, EventArgs e)
        {
            this.SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2010Black);
        }

        private void tsChoixOffice2010Argent_Click(object sender, EventArgs e)
        {
            this.SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2010Silver);
        }

        private void tsChoixOffice2010Bleu_Click(object sender, EventArgs e)
        {
            this.SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2010Blue);
        }

        private void tsChoixOffice2007Bleu_Click(object sender, EventArgs e)
        {
            this.SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2007Blue);
        }

        private void tsChoixOffice2007Argent_Click(object sender, EventArgs e)
        {
            this.SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2007Silver);
        }

        private void tsChoixOffice2007Noir_Click(object sender, EventArgs e)
        {
            this.SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2007Black);
        }

        private void tsChoixSparkleBleu_Click(object sender, EventArgs e)
        {
            this.SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager.SparkleBlue);
        }

        private void tsChoixSparkleOrange_Click(object sender, EventArgs e)
        {
            this.SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager.SparkleOrange);
        }

        private void tsChoixSparkleViolet_Click(object sender, EventArgs e)
        {
            this.SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager.SparklePurple);
        }

        private void tsChoixProSystem_Click(object sender, EventArgs e)
        {
            this.SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager.ProfessionalSystem);
        }

        private void tsChoixProOffice2003_Click(object sender, EventArgs e)
        {
            this.SwitchInterface(ComponentFactory.Krypton.Toolkit.PaletteModeManager.ProfessionalOffice2003);
        }
        #endregion

        private void kBtnEditMenu_Click(object sender, EventArgs e)
        {
            OrionMenuForm omf = new OrionMenuForm("Gestion des lignes de menus");
            omf.NameFormA = "OrionMenuForm";
            omf.SetMdiParent(this);
            omf.Show((Int32)kMenuListe.SelectedValue);
        }

        private void kMenuListe_SelectedValueChanged(object sender, EventArgs e)
        {
            this.RempliLigneMenu();
        }
        
        private void Main_Load(object sender, EventArgs e)
        {
            tsUser.Text = ((OrionUser)CallContext.GetData(OrionConfBase.OrionUserConnected)).NomLong +
                "(" + ((OrionGroup)CallContext.GetData(OrionConfBase.OrionUserGroupConnected)).Libelle + " - ";
            if (((Boolean)CallContext.GetData(OrionConfBase.OrionUserIsAdmin)))
                tsUser.Text += "Admin)";
            else
            {
                tsUser.Text += "Utilisateur)";
                kBtnEditMenu.Visible = false;
            }

            tsMat.Text = Environment.MachineName;
            tsDataBase.Text = ConfigurationManager.AppSettings["OrionBD"] + "(" + ConfigurationManager.AppSettings["OrionServeur"] + ")";

            RempliskCbMenu();

            this.kMenuListe.SelectedValue = ((OrionUser)CallContext.GetData(OrionConfBase.OrionUserConnected)).OrionMenuId;
        }

        private void tvMenuMain_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (tvMenuMain.SelectedNode != null)
            {
                DaoOrionMenu daoOM = new DaoOrionMenu();
                OrionMenu om = daoOM.SelectById(Convert.ToInt32(tvMenuMain.SelectedNode.Name));

                if (om.ClasseName != string.Empty && om.FormTitle != string.Empty)
                    this.FocusSurFormEnfantSinonOuvre(om);
                else if (om.ClasseName != string.Empty && om.FormName == string.Empty)
                {
                    List<string> lParam = new List<string>();
                    lParam.Add("\"" + om.Libelle + "\"");
                    OrionOutils.Alerte(OrionConfBase.ErreurMenuParam, lParam);
                }
            }
        }

        private void FocusSurFormEnfantSinonOuvre(OrionMenu om)
        {
            bool cont = true;

            if (om.FormName == null)
                om.FormName = om.ClasseName;

            foreach (Form f in this.MdiChildren)
            {
                if (((OrionBaseDoubleForm)f).NameFormA.Equals(om.FormName))
                {
                    f.BringToFront();
                    cont = false;
                    break;
                }
            }
            if (cont)
            {
                Type objType = typeof(OrionApplication.OrionForm.OrionGroupForm);
                String sType = OrionConfBase.BaseFormNameSpace + "." + om.ClasseName + ", " + OrionConfBase.BaseFormNameSpace;
                System.Type t = Type.GetType(sType);
                object ofi = System.Activator.CreateInstance(t, om.FormTitle);

                List<object> o = new List<object>();
                o.Add(this);
                ofi.GetType().InvokeMember("SetMdiParent", BindingFlags.Default |
                                                    BindingFlags.Public | BindingFlags.NonPublic |
                                                    BindingFlags.Instance | BindingFlags.InvokeMethod,
                                                    null, ofi, o.ToArray());

                o = new List<object>();
                o.Add(om.FormName);
                ofi.GetType().InvokeMember("SetNameForm", BindingFlags.Default |
                                                    BindingFlags.Public | BindingFlags.NonPublic |
                                                    BindingFlags.Instance | BindingFlags.InvokeMethod,
                                                    null, ofi, o.ToArray());
                
                string[] sParamT = om.OrionParam.Split('|');
                foreach (string s in sParamT)
                {
                    string[] tab = s.Split(':');
                    object[] val;
                    if (tab[0] == "IsReadOnly")
                    {
                        val = new object[1]; val[0] = Convert.ToBoolean(tab[1]);
                        ofi.GetType().InvokeMember(tab[0], BindingFlags.SetField, null, ofi, val);
                    }
                    else if (tab[0] == "IsPanelTopReadOnly")
                    {
                        val = new object[1]; val[0] = Convert.ToBoolean(tab[1]);
                        ofi.GetType().InvokeMember(tab[0], BindingFlags.SetField, null, ofi, val);
                    }
                    else if (tab[0] == "IsPanelBottomReadOnly")
                    {
                        val = new object[1]; val[0] = Convert.ToBoolean(tab[1]);
                        ofi.GetType().InvokeMember(tab[0], BindingFlags.SetField, null, ofi, val);
                    }
                    else if (tab[0] == "Mode")
                    {
                        val = new object[1]; val[0] = Convert.ToString(tab[1]);
                        ofi.GetType().InvokeMember(tab[0], BindingFlags.SetField, null, ofi, val);
                    }
                    else if (tab[0] == "SQL")
                    {
                        val = new object[1]; val[0] = Convert.ToString(tab[1]);
                        ofi.GetType().InvokeMember(tab[0], BindingFlags.SetField, null, ofi, val);
                    }
                    else if (tab[0] == "IsPanelTopHidden")
                    {
                        val = new object[1]; val[0] = Convert.ToBoolean(tab[1]);
                        ofi.GetType().InvokeMember(tab[0], BindingFlags.SetField, null, ofi, val);
                    }
                    else if (tab[0] == "IsPanelBottomHidden")
                    {
                        val = new object[1]; val[0] = Convert.ToBoolean(tab[1]);
                        ofi.GetType().InvokeMember(tab[0], BindingFlags.SetField, null, ofi, val);
                    }
                    
                }


                ofi.GetType().InvokeMember("Show", BindingFlags.Default |
                                                    BindingFlags.Public | BindingFlags.NonPublic |
                                                    BindingFlags.Instance | BindingFlags.InvokeMethod,
                                                    null, ofi, null);
            }
        }

        private void kBtnRechMenu_Click(object sender, EventArgs e)
        {
            tvMenuMain.ExpandAll();
            if (kMenuCherche.Text.Trim() == string.Empty)
                RetabliCouleurArrierePlanArbre(tvMenuMain.Nodes);
            else
                this.SearchInNodes(tvMenuMain.Nodes);
        }

        private void SearchInNodes(TreeNodeCollection tnc)
        {
            foreach (TreeNode tn in tnc)
            {
                if (tn.Text.Contains(kMenuCherche.Text))
                    tn.BackColor = Color.Yellow;
                else
                    tn.BackColor = Color.Transparent;
                SearchInNodes(tn.Nodes);
            }
        }

        private void RetabliCouleurArrierePlanArbre(TreeNodeCollection tnc)
        {
            foreach (TreeNode tn in tnc)
            {
                tn.BackColor = Color.Transparent;
                RetabliCouleurArrierePlanArbre(tn.Nodes);
            }
        }

        private void kBtnSpecNettoieArbre_Click(object sender, EventArgs e)
        {
            kMenuCherche.Text = string.Empty;
            RetabliCouleurArrierePlanArbre(tvMenuMain.Nodes);
        }

        private void aProposDeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About a = new About();
            a.ShowDialog();
        }

        #region Réorganisation des fenêtres
        private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void horizontaleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void verticaleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }
        #endregion

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (OrionOutils.ChoixOuiNon(OrionConfBase.ConfirmQuit) == DialogResult.No)
                e.Cancel = true;
        }
    }
}
